package sitar.controllers;
import haxe.Md5;
import oboe.core.SigSlot;
import php.db.ResultSet;
import php.Lib;
import php.Session;

import data.UserData;

/**
 * ...
 * @author Felipe Manga
 */

class User extends SigSlot
{
	private var loggedIn:Bool;
	
	public function new() 
	{
		super();
		Session.start();
		loggedIn = Session.exists("UID");
	}
	
	@slot function getUserData():Void
	{
		var data = new UserData();
		var rec = Main.db.query("SELECT * FROM users WHERE id = %0", [Session.get("UID")]).next();
		data.id = rec.id;
		data.name = rec.name;
		data.photoURL = rec.photoURL;
		this.shortSignal( "onClientMessage", ["userData", [data]] );		
	}
	
	@slot function registerUser( name:String, mail:String, pass:String )
	{
		try
		{
			Main.db.query( "INSERT INTO users (name, mail, password) VALUES (%0, %1, %2)", [name, mail, Md5.encode(pass)] );
		}
		catch ( e:Dynamic )
		{
			var str:String = Std.string(e);
			var r = ~/Duplicate entry '([^']*)'/;
			if ( r.match(str) )
			{
				var val = r.matched(1);
				this.shortSignal( "onClientMessage", ["registrationFailed", [val + " already registered."]] );
				return;
			}
			// Lib.print(str);
			return;
		}
		
		this.shortSignal( "onClientMessage", ["registrationSuccess", []] );
	}
	
	@slot function logIn( mail:String, key:String )
	{
		var ret = Main.db.query( "SELECT id, password FROM users WHERE mail = %0", [mail] );
		
		if ( ret.length == 0 )
		{
			this.shortSignal( "onClientMessage", ["loginFailed", ["E-mail \"" + mail + "\" not found."]] );
		}
		else
		{
			var data = ret.next();
			if ( Md5.encode(key) != data.password )
			{
				this.shortSignal( "onClientMessage", ["loginFailed", ["Incorrect password"]] );
			}
			else
			{
				this.shortSignal( "onClientMessage", ["loginSuccess", []] );
				Session.set("UID", data.id);
				this.loggedIn = true;
			}
		}
	}
	
	@slot function logOut():Void
	{
		Session.remove("UID");
		this.loggedIn = false;
		this.shortSignal( "onClientMessage", ["loggedOut", []] );
	}
	
	@slot function checkPermit( action:String, data:Array<Dynamic>, ret:Array<Bool> ):Void
	{
		if ( !Session.exists("UID") )
		{
			ret[0] = switch( action )
			{
				case 
					"registerUser", 
					"logIn":
						true;
					
				default: false;
			}
			return;
		}
		
		if ( !Session.exists("permit") )
		{
			var rs = Main.db.query( "SELECT permit FROM users WHERE id = %0", [Session.get("UID")] ).next();
			var permits:Array<String> = rs.permit.split(",");
			permits.push("logOut");
			permits.push("getUserData");
			Session.set( "permit", permits );
		}
		
		if ( data.length > 0 )
		{
			ret[0] = Session.get("permit").indexOf( action + "(" + Std.string(data[0]) + ")" ) > -1;
		}
		
		if ( !ret[0] )
		{
			ret[0] = ( Session.get("permit").indexOf( action ) > -1 );
		}
	}
}